package com.ai.sb.controller;

import com.ai.sb.dto.WxModel;
import com.ai.sb.model.SbUser;
import com.ai.sb.service.SbUserService;
import com.ai.sb.util.HttpUtil;
import com.ai.sb.util.Result;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Date:  2018/6/11
 * Time:  14:27
 * Email: siy@hmgsoft.com
 * Created by siy
 */
@Api(value = "微信管理接口",tags = {"微信API"})
@RestController
@RequestMapping("wx")
public class WxController {
    private Logger logger = LoggerFactory.getLogger(WxController.class);
    @Value("${my-moblie.appid}")
    private String appid;
    @Value("${my-moblie.accountID}")
    private String  accountID;
    @Value("${my-moblie.backBaseUrl}")
    private String backBaseUrl;
    @Value("${my-moblie.forendUrl}")
    private String forendUrl;
    @Value("${my-moblie.authorize}")
    private String authorize;
    @Value("${my-moblie.getFansInfoByOauth2}")
    private String getFansInfoByOauth2;
    @Value("${my-moblie.sendCaptcha}")
    private String sendCaptcha;
    @Value("${my-moblie.telbindbycaptcha}")
    private String telbindbycaptcha;
    @Value("${my-moblie.getJsSignature}")
    private String getJsSignature;

    @Resource
    private SbUserService sbUserService;

    @ApiOperation(value = "微信初始化用户" ,notes = "参数：无")
    @GetMapping("getUserInfo")
    public void getUserInfoCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("getUserInfo获取code");
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        //这里要将你的授权回调地址处理一下，否则微信识别不了
        String redirect_uri= URLEncoder.encode(backBaseUrl+"wx/getUserInfoBack", "UTF-8");
        //简单获取openid的话参数response_type与scope与state参数固定写死即可
        StringBuffer url=new StringBuffer(authorize+"?redirect_uri="+redirect_uri+
                "&appid="+appid+"&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
        logger.info(url.toString());
        response.sendRedirect(url.toString());//这里请不要使用get请求单纯的将页面跳转到该url即可
    }

    @GetMapping("getUserInfoBack")
    public void  getUserInfoBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("进入getUserInfoBack回调");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String code = request.getParameter("code");//获取code
        RestTemplate template = new RestTemplate();
        String url = getFansInfoByOauth2+"?accountId={accountId}&code={code}";
        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("accountId", accountID);
        uriVariables.put("code", code);
        String rs = template.getForObject(url, String.class, uriVariables);
        JSONObject jsonObject = JSONObject.parseObject(rs);
        logger.info("获取openId结果{}",jsonObject);
        String status = (String) jsonObject.get("status");
        String state = "0";
        String openid = "";
        String telNum = null;
        String provinceCode = null;
        if(status.equals("0000")){
            state = "1";
            openid = (String) jsonObject.get("openId");
            telNum = (String) jsonObject.get("telNum");
            provinceCode = (String) jsonObject.get("provinceCode");
            if(telNum==null || telNum.equals("")){
                logger.info("用户未绑定");
                state = "3";
            }
            String validateCode = sbUserService.getCode();
            if(provinceCode!=null && !validateCode.equals("0")){
                if(!provinceCode.equals(validateCode)){
                    logger.info("用户非指定归属地");
                    state = "4";
                }
            }
        }else if(status.equals("3001")){
            openid = (String) jsonObject.get("openid");
            logger.info("用户未关注");
            state = "2";
        }
        StringBuffer backUrl = new StringBuffer(forendUrl+"#/home?state="+state);
        if(jsonObject.get("openId")!=null){//正常返回大写openId
            backUrl.append("&openId="+URLEncoder.encode((String) jsonObject.get("openId"), "UTF-8"));
        }
        if(jsonObject.get("openid")!=null){//小写openid文档指明3001时不会返回openid 实际返回了 不过是小写
            backUrl.append("&openId="+URLEncoder.encode((String) jsonObject.get("openid"), "UTF-8"));
        }
        //如果用户满足条件则初始化用户
        if(state.equals("1")){
            SbUser sbUser = new SbUser();
            sbUser.setOpenid(openid);
            sbUser.setTelNum(telNum);
            logger.info("初始化用户参数：{}",sbUser);
            Result urs = sbUserService.initUser(sbUser);
            logger.info("初始化结果,{}",urs);
        }
        logger.info("重定向前端：{}",backUrl.toString());
        response.sendRedirect(backUrl.toString());//登录状态发送

    }

    //获取验证码
    @ApiOperation(value = "获取验证码" ,notes = "参数：openId，telNum")
    @PostMapping("sendCode")
    public JSONObject sendCode(@RequestBody WxModel wxModel){
        logger.info("获取验证码，参数{}",wxModel);
        RestTemplate template = new RestTemplate();
        String url = sendCaptcha+"?openId={openId}&telNum={telNum}";
        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("openId", wxModel.getOpenId());
        uriVariables.put("telNum", wxModel.getTelNum());
        String rs = template.getForObject(url, String.class, uriVariables);
        logger.info("获取验证码,结果：{}",rs);
        JSONObject jsonObject = JSONObject.parseObject(rs);
        return jsonObject;
    }

    //绑定用户手机号
    @ApiOperation(value = "绑定用户手机号" ,notes = "参数：openId，telNum，captcha（短信验证码）")
    @PostMapping("loginBind")
    public JSONObject loginBind(@RequestBody WxModel wxModel){
        logger.info("绑定用户手机号,参数{}",wxModel);
        RestTemplate template = new RestTemplate();
        String url = telbindbycaptcha+"?openId={openId}&telNum={telNum}&captcha={captcha}";
        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("openId", wxModel.getOpenId());
        uriVariables.put("telNum", wxModel.getTelNum());
        uriVariables.put("captcha", wxModel.getCaptcha());
        String rs = template.getForObject(url, String.class, uriVariables);
        logger.info("绑定用户手机号,结果：{}",rs);
        JSONObject jsonObject = JSONObject.parseObject(rs);
        return jsonObject;
    }

    //获取jsapi_ticket
    @ApiOperation(value = "wx.config授权参数获取" ,notes = "参数：无")
    @GetMapping("getJSAPI")
    public JSONObject getJSAPI(){
        logger.info("进入获取JSAPI");
        Map map = new HashMap();
        map.put("accountId",accountID);
        map.put("url",forendUrl);
        String rs = HttpUtil.restTemplate(getJsSignature,map,String.class, HttpMethod.GET);
        JSONObject jsonObject = JSONObject.parseObject(rs);
        jsonObject.put("appId",appid);
        logger.info("获取结果：{}",jsonObject);
        return jsonObject;
    }


    @PostMapping("tttt")
    public TestBox tttt(@RequestBody TestBox testBox){
        System.out.println("=======================");
        System.out.println(testBox);
        System.out.println("=======================");
        return testBox;
    }
}
